package menu

import (
	"context"
	"jinrigaoping/api/platform/internal/svc"
	"jinrigaoping/api/platform/internal/types"

	"jinrigaoping/rpc/sys/sys"

	"github.com/spf13/cast"
	"github.com/zeromicro/go-zero/core/logx"
)

type MenuInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuInfoLogic {
	return &MenuInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuInfoLogic) MenuInfo(req *types.SysMenuInfoReq) (resp *types.SysMenuInfoRes, err error) {
	info, err := l.svcCtx.SysRpc.SysMenuInfo(l.ctx, &sys.SysMenuInfoReq{MenuId: req.Id})
	if err != nil {
		return nil, err
	}

	all, err := l.svcCtx.SysRpc.SysMenuList(l.ctx, &sys.SysMenuListReq{})
	if err != nil {
		return nil, err
	}

	var menuSuperior []string
	menuSuperior = getMenuSuperior(all.List, info.MenuId, menuSuperior)

	for i, j := 0, len(menuSuperior)-1; i < j; i, j = i+1, j-1 {
		menuSuperior[i], menuSuperior[j] = menuSuperior[j], menuSuperior[i]
	}

	return &types.SysMenuInfoRes{
		MenuId:       info.MenuId,
		ParentId:     info.ParentId,
		MenuSuperior: menuSuperior,
		Name:         info.Name,
		Path:         info.Path,
		Component:    info.Component,
		MenuType:     info.MenuType,
		Icon:         info.Icon,
		MenuSort:     info.MenuSort,
		Redirect:     info.Redirect,
		Title:        info.Title,
		IsHide:       info.IsHide,
		IsKeepAlive:  info.IsKeepAlive,
		IsAffix:      info.IsAffix,
		IsLink:       info.IsLink,
		IsIframe:     info.IsIframe,
		LinkUrl:      info.LinkUrl,
	}, nil
}

func getMenuSuperior(list []*sys.SysMenuInfoRes, menuId int64, menuSuperior []string) []string {
	for _, v := range list {
		if menuId == v.MenuId {
			if v.ParentId == 0 {
				return menuSuperior
			}
			menuSuperior = append(menuSuperior, cast.ToString(v.ParentId))
			return getMenuSuperior(list, v.ParentId, menuSuperior)
		}
	}
	return menuSuperior
}
